package com.warom.sdg.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.warom.sdg.model.UserEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户数据库帮助类
 * 负责用户数据的SQLite数据库操作
 */
public class UserDatabaseHelper extends SQLiteOpenHelper {
    private static final String TAG = "UserDatabaseHelper";
    
    // 数据库名称和版本
    private static final String DATABASE_NAME = "user_manager.db";
    private static final int DATABASE_VERSION = 1;
    
    // 用户表
    public static final String TABLE_USERS = "users";
    
    // 表字段
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_ROLE = "role";
    public static final String COLUMN_LAST_LOGIN_TIME = "last_login_time";
    
    // 创建用户表的SQL语句
    private static final String SQL_CREATE_USERS_TABLE =
            "CREATE TABLE " + TABLE_USERS + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT UNIQUE NOT NULL, " +
                    COLUMN_PASSWORD + " TEXT NOT NULL, " +
                    COLUMN_NAME + " TEXT, " +
                    COLUMN_ROLE + " TEXT NOT NULL, " +
                    COLUMN_LAST_LOGIN_TIME + " INTEGER" +
                    ")";
    
    // 单例模式
    private static UserDatabaseHelper instance;
    
    /**
     * 获取UserDatabaseHelper实例
     * @param context 上下文
     * @return UserDatabaseHelper实例
     */
    public static synchronized UserDatabaseHelper getInstance(Context context) {
        if (instance == null) {
            instance = new UserDatabaseHelper(context.getApplicationContext());
        }
        return instance;
    }
    
    /**
     * 构造函数
     * @param context 上下文
     */
    private UserDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_USERS_TABLE);
        
        // 初始化默认用户
        initDefaultUsers(db);
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 如果有数据库升级逻辑，在这里实现
        // 这里简单地删除旧表并创建新表
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        onCreate(db);
    }
    
    /**
     * 初始化默认用户
     * @param db 数据库
     */
    private void initDefaultUsers(SQLiteDatabase db) {
        try {
            LogUtils.logOperation("用户管理", "初始化", "开始初始化默认用户");
            
            // 检查是否已有用户
            Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_USERS, null);
            cursor.moveToFirst();
            int count = cursor.getInt(0);
            cursor.close();
            
            if (count == 0) {
                // 添加默认管理员用户
                ContentValues adminValues = new ContentValues();
                adminValues.put(COLUMN_USERNAME, "admin");
                adminValues.put(COLUMN_PASSWORD, "admin");
                adminValues.put(COLUMN_NAME, "管理员");
                adminValues.put(COLUMN_ROLE, UserEntity.ROLE_ADMIN);
                adminValues.put(COLUMN_LAST_LOGIN_TIME, System.currentTimeMillis());
                db.insert(TABLE_USERS, null, adminValues);
                
                // 添加默认操作员用户
                ContentValues operatorValues = new ContentValues();
                operatorValues.put(COLUMN_USERNAME, "operator");
                operatorValues.put(COLUMN_PASSWORD, "operator");
                operatorValues.put(COLUMN_NAME, "操作员");
                operatorValues.put(COLUMN_ROLE, UserEntity.ROLE_OPERATOR);
                operatorValues.put(COLUMN_LAST_LOGIN_TIME, System.currentTimeMillis());
                db.insert(TABLE_USERS, null, operatorValues);
                
                // 添加默认查看员用户
                ContentValues viewerValues = new ContentValues();
                viewerValues.put(COLUMN_USERNAME, "viewer");
                viewerValues.put(COLUMN_PASSWORD, "viewer");
                viewerValues.put(COLUMN_NAME, "查看员");
                viewerValues.put(COLUMN_ROLE, UserEntity.ROLE_VIEWER);
                viewerValues.put(COLUMN_LAST_LOGIN_TIME, System.currentTimeMillis());
                db.insert(TABLE_USERS, null, viewerValues);
                
                LogUtils.logOperation("用户管理", "初始化结果", "成功创建默认用户");
            } else {
                LogUtils.logOperation("用户管理", "初始化结果", "已存在用户数据，跳过初始化");
            }
        } catch (Exception e) {
            Log.e(TAG, "初始化默认用户失败", e);
            LogUtils.logError("用户管理", "初始化默认用户失败", e);
        }
    }
    
    /**
     * 获取所有用户
     * @return 用户列表
     */
    public List<UserEntity> getAllUsers() {
        List<UserEntity> users = new ArrayList<>();
        
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_USERS,
                null,
                null,
                null,
                null,
                null,
                COLUMN_ID + " ASC"
        );
        
        try {
            if (cursor.moveToFirst()) {
                do {
                    UserEntity user = new UserEntity();
                    user.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
                    user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
                    user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)));
                    user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
                    user.setRole(cursor.getString(cursor.getColumnIndex(COLUMN_ROLE)));
                    user.setLastLoginTime(cursor.getLong(cursor.getColumnIndex(COLUMN_LAST_LOGIN_TIME)));
                    
                    users.add(user);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e(TAG, "获取用户列表失败", e);
            LogUtils.logError("用户管理", "获取用户列表失败", e);
        } finally {
            cursor.close();
        }
        
        return users;
    }
    
    /**
     * 根据ID获取用户
     * @param id 用户ID
     * @return 用户对象，如果不存在则返回null
     */
    public UserEntity getUserById(long id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_USERS,
                null,
                COLUMN_ID + " = ?",
                new String[]{String.valueOf(id)},
                null,
                null,
                null
        );
        
        UserEntity user = null;
        
        try {
            if (cursor.moveToFirst()) {
                user = new UserEntity();
                user.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
                user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
                user.setRole(cursor.getString(cursor.getColumnIndex(COLUMN_ROLE)));
                user.setLastLoginTime(cursor.getLong(cursor.getColumnIndex(COLUMN_LAST_LOGIN_TIME)));
            }
        } catch (Exception e) {
            Log.e(TAG, "获取用户失败", e);
            LogUtils.logError("用户管理", "获取用户失败", e);
        } finally {
            cursor.close();
        }
        
        return user;
    }
    
    /**
     * 根据用户名获取用户
     * @param username 用户名
     * @return 用户对象，如果不存在则返回null
     */
    public UserEntity getUserByUsername(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_USERS,
                null,
                COLUMN_USERNAME + " = ?",
                new String[]{username},
                null,
                null,
                null
        );
        
        UserEntity user = null;
        
        try {
            if (cursor.moveToFirst()) {
                user = new UserEntity();
                user.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
                user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
                user.setRole(cursor.getString(cursor.getColumnIndex(COLUMN_ROLE)));
                user.setLastLoginTime(cursor.getLong(cursor.getColumnIndex(COLUMN_LAST_LOGIN_TIME)));
            }
        } catch (Exception e) {
            Log.e(TAG, "获取用户失败", e);
            LogUtils.logError("用户管理", "获取用户失败", e);
        } finally {
            cursor.close();
        }
        
        return user;
    }
    
    /**
     * 添加用户
     * @param user 用户对象
     * @return 新增用户的ID，如果失败则返回-1
     */
    public long addUser(UserEntity user) {
        SQLiteDatabase db = this.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, user.getUsername());
        values.put(COLUMN_PASSWORD, user.getPassword());
        values.put(COLUMN_NAME, user.getName());
        values.put(COLUMN_ROLE, user.getRole());
        values.put(COLUMN_LAST_LOGIN_TIME, user.getLastLoginTime());
        
        long id = -1;
        
        try {
            id = db.insert(TABLE_USERS, null, values);
            LogUtils.logOperation("用户管理", "添加用户", "添加用户: " + user.getUsername());
        } catch (Exception e) {
            Log.e(TAG, "添加用户失败", e);
            LogUtils.logError("用户管理", "添加用户失败", e);
        }
        
        return id;
    }
    
    /**
     * 更新用户
     * @param user 用户对象
     * @return 更新是否成功
     */
    public boolean updateUser(UserEntity user) {
        SQLiteDatabase db = this.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, user.getUsername());
        values.put(COLUMN_PASSWORD, user.getPassword());
        values.put(COLUMN_NAME, user.getName());
        values.put(COLUMN_ROLE, user.getRole());
        values.put(COLUMN_LAST_LOGIN_TIME, user.getLastLoginTime());
        
        int rowsAffected = 0;
        
        try {
            rowsAffected = db.update(
                    TABLE_USERS,
                    values,
                    COLUMN_ID + " = ?",
                    new String[]{String.valueOf(user.getId())}
            );
            
            if (rowsAffected > 0) {
                LogUtils.logOperation("用户管理", "更新用户", "更新用户: " + user.getUsername());
            }
        } catch (Exception e) {
            Log.e(TAG, "更新用户失败", e);
            LogUtils.logError("用户管理", "更新用户失败", e);
        }
        
        return rowsAffected > 0;
    }
    
    /**
     * 删除用户
     * @param id 用户ID
     * @return 删除是否成功
     */
    public boolean deleteUser(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        
        int rowsAffected = 0;
        
        try {
            // 先获取用户信息，用于日志记录
            UserEntity user = getUserById(id);
            
            if (user != null) {
                rowsAffected = db.delete(
                        TABLE_USERS,
                        COLUMN_ID + " = ?",
                        new String[]{String.valueOf(id)}
                );
                
                if (rowsAffected > 0) {
                    LogUtils.logOperation("用户管理", "删除用户", "删除用户: " + user.getUsername());
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "删除用户失败", e);
            LogUtils.logError("用户管理", "删除用户失败", e);
        }
        
        return rowsAffected > 0;
    }
    
    /**
     * 更新用户最后登录时间
     * @param id 用户ID
     * @param lastLoginTime 最后登录时间
     * @return 更新是否成功
     */
    public boolean updateLastLoginTime(long id, long lastLoginTime) {
        SQLiteDatabase db = this.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(COLUMN_LAST_LOGIN_TIME, lastLoginTime);
        
        int rowsAffected = 0;
        
        try {
            rowsAffected = db.update(
                    TABLE_USERS,
                    values,
                    COLUMN_ID + " = ?",
                    new String[]{String.valueOf(id)}
            );
        } catch (Exception e) {
            Log.e(TAG, "更新用户登录时间失败", e);
            LogUtils.logError("用户管理", "更新用户登录时间失败", e);
        }
        
        return rowsAffected > 0;
    }
    
    /**
     * 验证用户登录
     * @param username 用户名
     * @param password 密码
     * @return 用户对象，如果验证失败则返回null
     */
    public UserEntity verifyLogin(String username, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_USERS,
                null,
                COLUMN_USERNAME + " = ? AND " + COLUMN_PASSWORD + " = ?",
                new String[]{username, password},
                null,
                null,
                null
        );
        
        UserEntity user = null;
        
        try {
            if (cursor.moveToFirst()) {
                user = new UserEntity();
                user.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
                user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
                user.setRole(cursor.getString(cursor.getColumnIndex(COLUMN_ROLE)));
                user.setLastLoginTime(cursor.getLong(cursor.getColumnIndex(COLUMN_LAST_LOGIN_TIME)));
                
                // 更新最后登录时间
                updateLastLoginTime(user.getId(), System.currentTimeMillis());
            }
        } catch (Exception e) {
            Log.e(TAG, "验证用户登录失败", e);
            LogUtils.logError("用户管理", "验证用户登录失败", e);
        } finally {
            cursor.close();
        }
        
        return user;
    }
} 